package com.yatop.lambda.api.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.yuyaogc.lowcode.engine.loader.Loader;
import com.yuyaogc.lowcode.engine.loader.SdkLoader;
import com.yuyaogc.lowcode.engine.plugin.Plugins;
import com.yuyaogc.lowcode.engine.plugin.activerecord.ActiveRecordPlugin;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;

@Configuration
public class EngineConfig {
    final static Plugins me = new Plugins();

    @Bean
    @ConfigurationProperties(prefix = "lambda-portal.db-datasource")
    public DataSource xaDataSource() throws Exception {
        return new DruidDataSource();
    }

    @Bean
    public Loader run(DataSource dataSource) throws Exception {
        ActiveRecordPlugin arp = new ActiveRecordPlugin("master", dataSource);
        me.add(arp);

        Loader.setLoader(new SdkLoader());
        Loader.getLoader().loadPlugin(me);
        Loader.getLoader().setUp();
        return Loader.getLoader();
    }

    public void destroy() {
        System.out.println("Bean is being destroyed. Cleaning up resources...");
        // 在这里执行清理操作，例如关闭线程池、释放文件句柄等
        Loader.getLoader().shutdown();
    }
}
